Ext.extend(app.module,{
    currentFormValues: {},
    init: function(){
        var main = this;
        //用于列表
        this.ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'tiku/tikus.do'}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'type'},
                {name:'typename'},
                {name:'title'},
                {name:'mark'},
                {name:'kemuid'},
                {name:'kemuname'},
                {name:'zhang'},
                {name:'filename'}
            ])
        });
        // 翻页排序时带上查询条件
//        this.ds.on('beforeload', function() {
//            this.baseParams = {
//                name : Ext.getCmp('queryName').getValue(),
//                tikuname : Ext.getCmp('querytikuName').getValue(),
//                deptids : Ext.getCmp('queryDept').getValue()
//            };
//        });

        var tiku_pagesize_combo = new Ext.form.ComboBox( {       //设置分页栏的每页记录数选择
            name : 'pagesize',
            hiddenName : 'pagesize',
            typeAhead : true,
            triggerAction : 'all',
            lazyRender : true,
            mode : 'local',
            store : new Ext.data.ArrayStore(
                {
                    fields : [ 'value', 'text' ],
                    data : [ [ 10, '10条/页' ], [ 20, '20条/页' ],
                        [ 50, '50条/页' ], [ 100, '100条/页' ],
                        [ 250, '250条/页' ], [ 500, '500条/页' ] ]
                }),
            valueField : 'value',
            displayField : 'text',
            value : '20',
            editable : false,
            width : 85
        });
        var number = parseInt(tiku_pagesize_combo.getValue());

        tiku_pagesize_combo.on("select", function(comboBox) {
            var bbar = Ext.getCmp('tikubbar');
            bbar.pageSize = parseInt(comboBox.getValue());
            number = parseInt(comboBox.getValue());
            main.ds.reload( {
                params : {
                    start : 0,
                    limit : bbar.pageSize
                }
            });
        });

        this.sm = new Ext.grid.CheckboxSelectionModel();
        this.body = new Ext.grid.GridPanel({
            store: this.ds,
            region: 'center',
            loadMask: true,
            viewConfig:{
                forceFit:true
            },
            sm: this.sm,
            columns: [
                new Ext.grid.RowNumberer(),
                this.sm,
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'id',
                    header: 'id',
                    hidden: true
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'type',
                    hidden: true
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'title',
                    header: '题干',
                    width: 240
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'mark',
                    header: '分值',
                    width: 20
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'zhang',
                    header: '章节',
                    width: 20
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'typename',
                    header: '题型',
                    width: 40
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'kemuname',
                    header: '科目',
                    width: 60
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'filename',
                    header: '素材',
                    width: 60
                }
            ],
            tbar: {
                xtype: 'toolbar',
                items: [
                    {
                        text: '新增',
                        iconCls : 'btn-new',
                        scope: this
                        //handler: this.add
                    },
                    '-',
                    {
                        text: '修改',
                        iconCls : 'btn-edit',
                        scope: this
                        //handler: this.edit
                    },
                    '-',
                    {
                        text: '删除',
                        iconCls : 'btn-del',
                        scope: this
                        //handler: this.del
                    },
                    '-',
                    {
                        text: '导入',
                        iconCls : 'btn-save',
                        scope: this,
                        handler: this.importFromExcel
                    },
                    '->',
                    {
                        xtype: 'displayfield',
                        value: '查询条件：'
                    },
                    ' ',
                    {
                        xtype: 'textfield',
                        id : 'queryQuestionTitle',
                        name : 'queryQuestionTitle',
                        emptyText : '请输入题干',
                        enableKeyEvents : true,
                        listeners : {
                            specialkey : function(field, e) {
                                if (e.getKey() == Ext.EventObject.ENTER) {
                                    main.query();
                                }
                            }
                        },
                        width : 100
                    },
                    {
                        text : '查询',
                        iconCls : 'btn-search',
                        handler : function() {
                            main.query();
                        }
                    }

                ]
            },
            bbar: {
                id: 'tikubbar',
                xtype: 'paging',
                pageSize : number,
                store : this.ds,
                displayInfo : true,
                displayMsg : '显示{0}条到{1}条,共{2}条',
                emptyMsg : "没有符合条件的记录",
                items : [ '-', '&nbsp;&nbsp;', tiku_pagesize_combo ]
            }
        });
        this.main.add(this.body);
        this.main.doLayout();
        this.ds.load({
            params: {
                start:0,
                limit:20
            }
        });
        this.render();
    },

    getImportrDlg: function(){
        var dlg = new Ext.Window({
            height: 200,
            width: 400,
            layout: 'fit',
            border: false,
            frame: true,
            title: '',
            closeAction: 'hide',
            modal: true,
            plain: true,
            resizable: false,
            items: [this.importForm],
            listeners: {
                scope: this,
                render: function(fp){
                    this.importForm.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = this.importForm.getForm();
                    f.reset();
                    f.clearInvalid();
                }
            }
        });
        return dlg;
    },

    getImportForm: function(){
        var main = this;
        var kemuStore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'kemu/getAllKemus.do'}),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'}
            ])
        });
        var comboKemu = new Ext.form.ComboBox({
            store: kemuStore,
            editable: false,
            emptyText: '请选择科目...',
            allowBlank: false,
            mode: 'remote',
            hiddenName : 'kemuid',
            typeAhead : true,
            triggerAction : 'all',
            displayField: 'name',
            valueField: 'id',
            fieldLabel: '选择科目'
        });
        var form = new Ext.form.FormPanel({
            labelAlign: 'right',
            bodyStyle: 'padding:5px',
            buttonAlign: 'right',
            frame: true,
            fileUpload: true,
            url:'tiku/importTikuFromExcel.do',
            labelWidth: 80,
            defaults: {
                anchor: '90%'
            },
            items: [
                comboKemu,
                {
                    xtype: 'textfield',
                    name: 'file',
                    allowBlank: false,
                    id: 'tikuExcel',
                    fieldLabel: '选择文件',
                    inputType: 'file'
                }
            ],
            buttons: [{
                text: '提交',
                scope: this,
                handler: function() {
                    this.submitImport();
                }
            }]
        });
        return form;
    },

    submitImport: function(){
        if (this.importForm.getForm().isValid()) {
            this.importForm.getForm().submit({
                waitTitle: '保存数据',
                waitMsg: '正在保存……',
                scope: this,
                method: 'post',
                params: '',
                submitEmptyText: false,     //禁止提交emptyText
                success: function(form, action) {
                    this.ds.reload();
                    var info = action.result.info;
                    if (action.result.success) {
                        this.ds.reload();
                        this.importForm.getForm().reset();
                        this.imporDlg.hide();
                    }
                    Ext.Msg.alert('信息', info);
                },
                failure: function(form, action) {
                    this.ds.reload();
                    var info = action.result.info;
                    Ext.Msg.alert('提示', info);
                }
            });
        }
    },
    submit: function(){
        if (this.form.getForm().isValid()) {
            var id = this.form.getForm().findField("id").getValue();
            this.form.getForm().submit({
                waitTitle: '保存数据',
                waitMsg: '正在保存……',
                scope: this,
                method: 'post',
                params: '',
                submitEmptyText: false,     //禁止提交emptyText
                success: function(form, action) {
                    var info = action.result.info;
                    if (action.result.success) {
                        this.ds.reload();
                        if (action.result.method == "Create") {
                            this.form.getForm().reset();
                        } else {
                            this.dlg.hide();
                        }
                    }
                    Ext.Msg.alert('信息', info);
                },
                failure: function(form, action) {
                    var info = action.result.info;
                    Ext.Msg.alert('提示', info);
                }
            });
        }
    },
    add: function() {
        Ext.apply(this.currentFormValues, {
            id: '',
            name: "",
            tikuname: "",
            deptid: ""
        });
        this.comboxWithDeptTree.setValue('');
        this.dlg.setTitle("增加题目");
        this.dlg.show();
    },

    edit: function() {
        var recs = this.body.getSelectionModel().getSelections();
        if (recs.length==0) {
            Ext.Msg.alert('信息', '请选择要编辑的题目。');
        } else if(recs.length>1) {
            Ext.Msg.alert('信息', '只能选择一道题目进行编辑。');
        } else {
            this.dlg.setTitle("编辑题目");
            Ext.apply(this.currentFormValues, {
                id: recs[0].data.id,
                name: recs[0].data.name,
                tikuname: recs[0].data.tikuname,
                deptid: recs[0].data.deptid
            });
            this.comboxWithDeptTree.setValue(recs[0].data.deptname);
            this.dlg.show();
        }
    },

    del: function() {
        var main = this;
        if (this.body.getSelectionModel().hasSelection()) {
            var recs = this.body.getSelectionModel().getSelections();
            var ids = [];
            var titles = [];
            for (var i = 0; i < recs.length; i++) {
                var data = recs[i].data;
                ids.push(data.id);
                titles.push(data.name);
            }
            Ext.Msg.confirm('删除题目', '确定删除以下题目？<br><font color="red">' + titles.toString() + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        Ext.Ajax.request({
                            method:'post',
                            url:'tiku/remove.do',
                            params:{
                                ids:ids.toString()
                            },
                            scope: main,
                            success: function(resp, opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                if(result.success=='true') {
                                    this.ds.reload();
                                    Ext.Msg.alert('信息', info);
                                }else {
                                    Ext.Msg.alert('信息', info);
                                }
                            },
                            failure: function(resp,opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                Ext.Msg.alert('提示', info);
                            }
                        });
                    }
                });
        } else {
            Ext.Msg.alert('信息', '请选择要删除的题目！');
        }
    },
    importFromExcel: function(){
        this.imporDlg.setTitle("导入题库");
        this.imporDlg.show();
    },
    query: function(){
        this.ds.load( {
            params : {
                start : 0,
                limit : Ext.getCmp('tikubbar').pageSize,
                name : Ext.getCmp('queryName').getValue(),
                tikuname : Ext.getCmp('querytikuName').getValue(),
                deptids : Ext.getCmp('queryDept').getValue()
            }
        });
    },
    render: function() {
//        if (!this.form) {
//            this.form = this.getForm();
//        };
//        if (!this.dlg) {
//            this.dlg = this.getDialog();
//        };
        if (!this.importForm) {
            this.importForm = this.getImportForm();
        };
        if (!this.imporDlg) {
            this.imporDlg = this.getImportrDlg();
        };
    }
});